package app

import (
	"fmt"
	"log/slog"

	"github.com/go-playground/validator/v10"
	"gitverse.ru/dlc/similarity-compiler/internal/config"
	"gitverse.ru/dlc/similarity-compiler/internal/initialize"
	"gitverse.ru/dlc/similarity-compiler/internal/initialize/grpc"
	"gitverse.ru/dlc/similarity-compiler/internal/server"
	"gitverse.ru/dlc/similarity-compiler/pkg/closer"
	"gitverse.ru/dlc/similarity-compiler/pkg/errors"
)

type grpcDeps struct {
	Logger   *slog.Logger         `validate:"required"`
	Closer   *closer.Closer       `validate:"required"`
	Config   *config.Config       `validate:"required"`
	Services *initialize.Services `validate:"required"`
}

func setupGRPC(deps grpcDeps) errors.Error {
	if err := validator.New().Struct(deps); err != nil {
		return errors.NewWithError(fmt.Errorf("validate grpcDeps: %w", err), errors.ErrInternalError)
	}

	controllers, err := grpc.NewControllers(grpc.ControllersDeps{
		Services: deps.Services,
	})
	if err != nil {
		return err.Wrap("init controllers")
	}

	grpc, err := server.NewGRPC(server.DepsGRPC{
		Config: deps.Config.GRPC,
		Logger: deps.Logger,
	})
	if err != nil {
		return err.Wrap("init grpc server")
	}

	grpc.Register(server.Controllers{
		Compiler: controllers.Compiler,
	})

	deps.Closer.Add(closer.Wrap(grpc.Server.GracefulStop))

	return nil
}
